<?php

class FinLedgerController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    public function actionGetFinLedgerList($page=1, $sort=NULL, $accountid=NULL,$transid=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;
        $order=CJSON::decode($sort);
        $crit=new CDbCriteria();
        $crit->order=isset($order)?$order[0]['property'].' '.$order[0]['direction']:'AddedDate DESC';
       
        if($accountid!=NULL){
            $crit->compare('accountid', $accountid);
            
        }
        if($transid!=NULL){
            $crit->compare('transid', $transid);
        }
        
        $ledger = new CActiveDataProvider('FinLedger', array(
                    'criteria' => $crit,
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $ledgerList = array();
        if ($ledger->getTotalItemCount() > 0) {
            $ledgerList['totalCount'] = $ledger->getTotalItemCount();
            $ledgerList['type'] = 'EmpGroup';
            foreach ($ledger->getData() as $i=>$item) {
                $ledgerList['data'][] = $item->getAttributes();
                $ledgerList['data'][$i]['accountname']=Coa::model()->getAccountName($item->accountid);
                $ledgerList['data'][$i]['accountdesc']=$item->accountid.' - '.Coa::model()->getAccountName($item->accountid);
                
                if($item->modifiedby!=NULL){
                    $ledgerList['data'][$i]['modifiedby']=getUserRealname($item->modifiedby);
                }
                if($item->jobclassid!=NULL){
                    $ledgerList['data'][$i]['jobclasstext']=JobsClass::getText($item->jobclassid);
                }
                if($item->getAmountType()==FinLedger::CREDIT){
                    $ledgerList['data'][$i]['credit']=abs(number_format($item->amount,2));
                    $ledgerList['data'][$i]['debit']=NULL;
                }elseif($item->getAmountType()==FinLedger::DEBIT){
                    $ledgerList['data'][$i]['debit']=abs(number_format($item->amount,2));
                    $ledgerList['data'][$i]['credit']=NULL;
                }
            }
            echo json_encode($ledgerList);
        }
        Yii::app()->end();
    }
    
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new FinLedger;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

       if (isset($_POST['FinLedger'])) {
            $model->attributes = $_POST['FinLedger'];
            
            if ($model->save()){
                echo "Save successful";
            }else{
                echo json_encode($model->getErrors());
            }
                
        }

    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['FinLedger'])) {
            $model->attributes = $_POST['FinLedger'];
            if ($model->save()){
                echo "Save successful";
            }else{
                echo json_encode($model->getErrors());
            }
                
        }

    }

   

    /**
     * Lists all models.
     */
    public function actionIndex() {

        outputJsByList(FinLedger::model()->getAllCoaList(), 'accountsList');
        outputJsByList(Jobs::model()->getList(), 'jobList');
        outputJsByList(JobsClass::getList(), 'jobClassList');
        $this->render('index', array(
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = FinLedger::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'fin-ledger-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionAccountIncreasesDecreases($account) {
        $rs = Coa::model()->getAccountIncreasesDecreases($account);
        echo CJSON::encode($rs);
    }

    public function actionSaveJournalEntry() {
        $error=NULL;
        if (isset($_POST['journalData'])) {
            $data = $_POST['journalData'];
            if(count($data)<2){
                echo 'Need more than 2 row';
                return;
            }
            $modelArray=array();
            $balance=0;
            $tranid=createRandomUUID();
            $tranCount=0;
            foreach ($data as $item) {
                $tranCount++;
                $journal=NULL;
                if(isset($item['entryid']) && $item['entryid']!=NULL){
                    $journal=FinLedger::model()->find('entryid=:entryid',array(
                        'entryid'=>$item['entryid']
                    ));
                    $journal->accountid=$item['accountid'];
                    $journal->transmemo=$item['transmemo'];
                    $journal->docnum=$item['docnum'];
                    $journal->jobid=$item['jobid'];
                    $journal->jobclassid=$item['jobclassid'];
                    $journal->transtype=$item['transtype'];
                    $journal->units=$item['units'];
                    $journal->deptid=$item['deptid'];
                }else{
                    //create new entry
                    $journal=new FinLedger;                
                    $journal->accountid=$item['accountid'];
                    $journal->transid=$tranid;
                    $journal->trancount=$tranCount;
                    $journal->transdate=date('Y-m-d H:i:s');
                    $journal->source=200;
                }
                $journal->transdate=$_POST['dateAdded'];
                $journal->transdesc=$_POST['transDesc'];
                //checking
                if($item['debit']>0 && $item['credit']>0){
                    echo 'Only have a debit or credit';
                    return;
                }
                $inde=Coa::model()->getAccountIncreasesDecreases($item['accountid']);
                
                if($item['debit']>0){ //type debit
                    
                    $balance+=$item['debit'];
                    $journal->amount=$item['debit'];
                    if($inde[Coa::DEBIT]==Coa::DECREASE){
                        $journal->amount*=-1;
                    }
                }elseif($item['credit']>0){
                    //type credit
                    $balance-=$item['credit'];
                    $journal->amount=$item['credit'];
                    if($inde[Coa::CREDIT]==Coa::DECREASE){
                        $journal->amount*=-1;
                    }
                }
                
                $modelArray[]=$journal;
               
            }
            
            //save all item
            foreach($modelArray as $model){
                if( ! $model->save()){
                    echo json_encode($model->getErrors());
                }
            }
        }
    }

}
